package pw.hais.seriaport.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.List;

import android_serialport_api.CHexConver;
import android_serialport_api.ChuanKouUtils;
import android_serialport_api.DevicesInfo;
import pw.hais.seriaport.R;
import pw.hais.seriaport.adapter.SpinnerAdapter;
import pw.hais.utils.EmptyUtil;
import pw.hais.utils.L;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private ChuanKouUtils chuanKou;

    private Spinner spinner_baudrate, spinner_databits, spinner_stopbits, spinner_parity, spinner_device;
    private EditText edit_post_mssage;
    private Button button_post_str, button_post_hex;
    private TextView text_log, text_serial_info;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //缩下小键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        //获取控件
        edit_post_mssage = (EditText) findViewById(R.id.edit_post_mssage);
        text_serial_info = (TextView) findViewById(R.id.text_serial_info);
        text_log = (TextView) findViewById(R.id.text_log);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        findViewById(R.id.btn_update).setOnClickListener(this);
        button_post_str = (Button) findViewById(R.id.button_post_str);
        button_post_hex = (Button) findViewById(R.id.button_post_hex);
        button_post_str.setOnClickListener(this);
        button_post_hex.setOnClickListener(this);
        //比特率
        spinner_baudrate = (Spinner) findViewById(R.id.spinner_baudrate);
        spinner_baudrate.setAdapter(new SpinnerAdapter(getResources().getStringArray(R.array.baudrate)));
        spinner_baudrate.setOnItemSelectedListener(this);
        //数据位
        spinner_databits = (Spinner) findViewById(R.id.spinner_databits);
        spinner_databits.setAdapter(new SpinnerAdapter(getResources().getStringArray(R.array.databits)));
        spinner_databits.setOnItemSelectedListener(this);
        //停止位
        spinner_stopbits = (Spinner) findViewById(R.id.spinner_stopbits);
        spinner_stopbits.setAdapter(new SpinnerAdapter(getResources().getStringArray(R.array.stopbits)));
        spinner_stopbits.setOnItemSelectedListener(this);
        //校验位
        spinner_parity = (Spinner) findViewById(R.id.spinner_parity);
        spinner_parity.setAdapter(new SpinnerAdapter(getResources().getStringArray(R.array.parity)));
        spinner_parity.setOnItemSelectedListener(this);
        //设备列表
        spinner_device = (Spinner) findViewById(R.id.spinner_device);
        try {
            List<DevicesInfo> CKList = ChuanKouUtils.getAllDevices();
            String[] arr = new String[CKList.size()];
            arr[0] = "";
            for (int i = 1; i < CKList.size(); i++) {
                arr[i] = CKList.get(i).path.replace("/dev/", "");
            }
            SpinnerAdapter device_adapter = new SpinnerAdapter(arr);
            spinner_device.setAdapter(device_adapter);
            spinner_device.setOnItemSelectedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
            L.showLong("检测不到串口端口,软件功能不可用！");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (chuanKou != null) chuanKou.closeSerialPort();
    }


    private int baudrate, databits, stopbits;
    private String parity, device;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        baudrate = Integer.parseInt(spinner_baudrate.getSelectedItem() + "");
        databits = Integer.parseInt(spinner_databits.getSelectedItem() + "");
        stopbits = Integer.parseInt(spinner_stopbits.getSelectedItem() + "");
        parity = spinner_parity.getSelectedItem() + "";
        device = spinner_device.getSelectedItem() + "";

        if (!EmptyUtil.emptyOfString(device)) {
            device = "/dev/" + device;
            L.showShort("串口正在初始化为：" + device);
            try {
                chuanKou = new ChuanKouUtils(device, baudrate, databits, stopbits, 'n') {
                    @Override
                    protected void onDataReceived(byte[] buffer, int size) {
                        try {
                            Log.i("ChuanKouInfo", "收到串口信息：" + ChuanKouUtils.showByte(buffer, size));
                            text_log.append("【收　  到】：" + ChuanKouUtils.showByte(buffer, size) + "\n");
                            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                button_post_str.setEnabled(true);
                button_post_hex.setEnabled(true);
            } catch (Exception e) {
                L.showLong("串口初始化【失败】：" + device);
                device = "";
                button_post_str.setEnabled(false);
                button_post_hex.setEnabled(false);
            }
        } else {
            device = "";
        }

        text_serial_info.setText("波特率：" + baudrate + "\n数据位：" + databits + "\n停止位：" + stopbits + "\n校验位：" + parity + "\n设备号：" + device);
    }


    @Override
    public void onClick(View v) {
        String mssage = edit_post_mssage.getText() == null ? "" : edit_post_mssage.getText().toString();
        try {
            switch (v.getId()) {
                case R.id.button_post_hex:
                    byte[] init = CHexConver.hexStr2Byte(mssage);
                    chuanKou.pushMsg(init);
                    text_log.append("【发Byte[]】：" + ChuanKouUtils.showByte(init, init.length) + "\n");
                    break;
                case R.id.button_post_str:
                    chuanKou.pushMsg(mssage);
                    text_log.append("【发String】：" + mssage + "\n");
                    break;
                case R.id.btn_update:
                    Uri uri_app = Uri.parse("http://app.hais.pw");
                    startActivity(new Intent(Intent.ACTION_VIEW, uri_app));
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            L.showLong("信息发送到 " + device + " 失败【" + mssage + "】");
        }
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }


    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_help) {
            startActivity(new Intent(this, AuthorActivity.class));
        } else if (id == R.id.action_author) {
            startActivity(new Intent(this, AuthorActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }
}
